﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;

namespace Sunny.Controls
{
	public class DropDownList : Telerik.Windows.Controls.RadComboBox
	{
		public bool AllowNull
		{
			get
			{
				return this.NullItem.Visibility == System.Windows.Visibility.Visible;
			}
			set
			{
				this.NullItem.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
			}
		}

		protected readonly Telerik.Windows.Controls.RadComboBoxItem NullItem = new Telerik.Windows.Controls.RadComboBoxItem { Content = "　", Visibility = System.Windows.Visibility.Collapsed };

		protected bool CodeTriggered;

		protected override void OnItemsSourceChanged(System.Collections.IEnumerable oldValue, System.Collections.IEnumerable newValue)
		{
			System.Collections.Generic.IEnumerable<object> items = newValue.OfType<object>();
			if (items.Count()==0|| items.First() != this.NullItem)
			{
				this.ItemsSource = new object[] { this.NullItem }.Concat(items);
				newValue = this.ItemsSource;
			}
			base.OnItemsSourceChanged(oldValue, newValue);
			if (this.AllowNull)
				return;
			//this.CodeTriggered = true;
			this.SelectedIndex = 1;
			//this.CodeTriggered = false;
		}

		protected override void OnSelectionChanged(SelectionChangedEventArgs e)
		{
			if (this.CodeTriggered)
				e.Handled = true;
			base.OnSelectionChanged(e);
		}

		protected override void OnPropertyChanged(System.Windows.DependencyPropertyChangedEventArgs e)
		{
			if (e.Property.Name == "ItemsSource")
				if (this.ItemsSource == null)
					this.Items.Clear();
			base.OnPropertyChanged(e);
		}

		public DropDownList()
		{
			this.Items.Insert(0, this.NullItem);
		}

		public virtual string ValueProperty
		{
			get
			{
				return "SelectedValue";
			}
		}

		public virtual object Value
		{
			get
			{
				return this.GetType().GetProperty(this.ValueProperty).GetValue(this, null);
			}
			set
			{
				this.GetType().GetProperty(this.ValueProperty).SetValue(this, value, null);
			}
		}
	}
}